<?php
namespace app\distribution\model;
use app\BaseModel;
use think\facade\Cache;

//*------------------------------------------------------ */
//-- 分销身份表
/*------------------------------------------------------ */
class DividendRoleModel extends BaseModel
{
	protected $table = 'distribution_dividend_role';
	public  $pk = 'role_id';
	protected static $mkey = 'distribution_dividend_role_list';
	
	 /*------------------------------------------------------ */
	//-- 清除缓存
	/*------------------------------------------------------ */ 
	public function cleanMemcache(){
		Cache::rm(self::$mkey);
	}
	/*------------------------------------------------------ */
	//-- 获取列表
	/*------------------------------------------------------ */ 
	public  function getRows(){
		$data = Cache::get(self::$mkey);
		if (empty($data) == false){
			return $data;
		}
        $data[0] = ['role_id'=>0,'role_name'=>'普通会员','id'=>0,'level'=>999,'name'=>'普通会员'];
        $rows = $this->field('*,role_id as id,role_name as name')->order('level DESC')->select()->toArray();
		foreach ($rows as $row){
            $row['upleve_value'] = json_decode($row['upleve_value'],true);
			$data[$row['role_id']] = $row;
		}
		Cache::set(self::$mkey,$data,600);
		return $data;
	}
	/*------------------------------------------------------ */
	//-- 获取角色信息
	/*------------------------------------------------------ */ 
	public function info($role_id,$returnName = false){
		$rows = $this->getRows();
		$rows[0] = ['role_name'=>'普通会员','role_id'=>0,'level'=>999];
		if ($returnName == true){
			return $rows[$role_id]['role_name'];
		}
		return $rows[$role_id];
	}
    /*------------------------------------------------------ */
    //-- 身份汇总
    /*------------------------------------------------------ */
    public function roleStatc(){
        $statc = Cache::get($this::$mkey . 'statc');
        if (empty($statc) == true){
            $where[] = ['role_id','>',0];
            $statc = (new \app\member\model\UsersModel)->where($where)->group('role_id')->column('count(user_id) as count','role_id');
            Cache::set($this::$mkey . 'statc', $statc, 30);
        }
        $data['allNum'] = 0;
        foreach ($statc as $val){
            $data['allNum'] += $val;
        }
        $list = $this->getRows();
        foreach ($list as $row){
            $num = 0;
            if (empty($statc[$row['role_id']]) == false){
                $num = $statc[$row['role_id']];
            }
            $data['statc'][$row['role_id']]['num'] = $num;
            $data['statc'][$row['role_id']]['pre'] = priceFormat($num / $data['allNum'] * 100);
        }
        return $data;
    }
}
